package com.lib.utils;

import android.os.Environment;

import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @author 一叶丶枫凌
 * 描述：显示一个类的所有字段方法
 * Created on 2018-10-15 下午 03:13
 */
public class ClassUtil {
    public static void showAll(Class<?> clz) {

        Method[] methods = clz.getDeclaredMethods();

        StringBuilder sb = new StringBuilder();
        sb.append("\n本类：").append(clz).append("\n");
        Field[] declaredFields = clz.getDeclaredFields();
        for (Field field : declaredFields) {
            sb.append(field.getType()).append(" : ").append(field.getName()).append(";\n");
        }
        for (Method method : methods) {
            sb.append(method.getReturnType()).append(" ").append(method.getName()).append(" ( ");
            Class<?>[] parameterTypes = method.getParameterTypes();
            for (int i = 0; i < parameterTypes.length; i++) {
                Class<?> aClass = parameterTypes[i];
                sb.append(aClass.getName()).append(".class");
                if (i < parameterTypes.length - 1) {
                    sb.append(", ");
                }
            }
            sb.append(" )\n");
        }
        XLog.i(clz.getName() + "----\n" + sb.toString());
    }

    public static void showAll(Class<?> clz, Object obj, boolean isNeedFile) {

        Method[] methods = clz.getDeclaredMethods();

        StringBuilder sb = new StringBuilder();
        sb.append("\n本类：").append(clz).append("\n");
        Field[] declaredFields = clz.getDeclaredFields();
        for (Field field : declaredFields) {
            field.setAccessible(true);
            Object o = null;
            try {
                o = field.get(obj);
            } catch (Exception ignored) {
            }
            sb.append(field.getType()).append(" : ").append(field.getName()).append(" = ").append(o).append(";\n");
        }
        for (Method method : methods) {
            sb.append(method.getReturnType()).append(" ").append(method.getName()).append(" ( ");
            Class<?>[] parameterTypes = method.getParameterTypes();
            for (int i = 0; i < parameterTypes.length; i++) {
                Class<?> aClass = parameterTypes[i];
                sb.append(aClass.getName()).append(".class");
                if (i < parameterTypes.length - 1) {
                    sb.append(", ");
                }
            }
            sb.append(" )\n");
        }
        String str = clz.getName() + "----\n" + sb.toString();
        XLog.i(str);
        if (isNeedFile) {
            File file = new File(Environment.getExternalStorageDirectory(), "/aaa.txt");
            FileUtils.writeFileFromString(file, str, false);
        }
    }
}